#include <stdio.h>
#include <fstream>

#include "rawncfileplugin.h"
#include "../../data/geometrydata.h"

using namespace PBVP;

DataInterface* RawNCFilePlugin::loadFile(const QString& fname)
{
    // Create a geometry datanode and add to the datamanager
	if (! fname.endsWith(".rawnc")) return NULL;

    int i, nv, nt;
	std::ifstream from (fname.toStdString().c_str());
	if(!from.is_open()) return NULL;
	// read header (number of vertex and triangles)
    from >> nv;
    from >> nt;
	GeometryData *pGeometry = new GeometryData();
	
	for(i = 0; i < nv; i++) {
		float x, y, z;
		float nx, ny, nz;
		float r, g, b;
		from >> x; from >> y; from >> z;
		from >> nx; from >> ny; from >> nz;
		from >> r; from >> g; from >> b;
		Vector3 vertex(x, y, z);
		Vector3 normal(nx, ny, nz);
		Vector3 color(r, g, b);
		pGeometry->addVertex(vertex, normal, color);
	}

	for(i = 0; i < nt; i++) {
		int index[3];
		from >> index[0];
		from >> index[1];
		from >> index[2];
		pGeometry->addTriangle(index);
	}	
	from.close();
	
#ifdef _DEBUG
	printf("add %s to datamanager\n", fname.toStdString().c_str());
#endif
	return pGeometry;
}

bool RawNCFilePlugin::saveFile(DataInterface *pData, const QString &fname)
{
	if(pData->getDataSetType() != GEOMETRY_DATA) return false;
	GeometryData *pGeoData = dynamic_cast<GeometryData *>(pData);
	if(!pGeoData) return false;
	std::ofstream out(fname.toStdString().c_str());
	if(!out.is_open()) return false;

	//write the header
	out << pGeoData->numOfVertices() << " " << pGeoData->numOfTriangles() << std::endl;
	for(unsigned int i = 0; i < pGeoData->numOfVertices(); i++) 
	{
		Vector3 v = pGeoData->getVertex(i);
		Vector3 n(0, 0, 1.0f);
		Vector3 c(0.8f, 0.8f, 0.2f);

		out << v.x << " " << v.y << " " << v.z;
		if (pGeoData->hasNormalArray())
		{
			n = pGeoData->getNormalVector(i);
		}
		if (pGeoData->hasColorArray())
		{
			c = pGeoData->getColorVector(i);
		}
		out << " " << n.x << " " << n.y << " " << n.z;
		out << " " << c.x << " " << c.y << " " << c.z;
		out << std::endl;
	}

	for(unsigned int i = 0; i < pGeoData->numOfTriangles(); i++)
	{
		unsigned int idx[3];
		pGeoData->getTriangleIndex(i, idx);
		out << idx[0] << " " << idx[1] << " " << idx[2] << std::endl;
	}
	out.close();
	return true;
}

Q_EXPORT_PLUGIN2(rawncfile, RawNCFilePlugin)
